package HomeWork.hw0606;

import javax.security.auth.login.FailedLoginException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: Hasee
 * @Date: 2020-06-06 18:27:20
 */
@WebServlet("/hw0606_5_1")
public class work5_1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String lastAccessTime=null;
        Cookie[] cookies=req.getCookies();
        for (int i=0;cookies!=null&&i<cookies.length;i++){
            if ("lastAccess".equals(cookies[i].getName())){
                lastAccessTime=cookies[i].getValue();

            }
        }
        if (lastAccessTime==null){
            resp.getWriter().print("首次访问");
        }else {
            resp.getWriter().print("您上次访问时间为："+lastAccessTime);
        }
        Date date=new Date();

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String d=sdf.format(date);
        Cookie cookie=new Cookie("lastAccess",d);
        cookie.setMaxAge(600);
        resp.addCookie(cookie);
    }
}
